<?php
/**
 * 商品管理
 * http://baseAddress/api/goods/
 */
namespace App\Http\Controllers\Api\Goods;

use App\Http\Controllers\Controller;
use App\Models\Goods\GoodsService;
use Illuminate\Http\Request;

class GoodsController extends Controller
{
    /**
     * 按条件查找商品信息
     * @param Request $request
     * @param GoodsService $goodsService
     * @return \Illuminate\Http\JsonResponse
     */
    public function query(Request $request, GoodsService $goodsService)
    {
        $data = $request->request->get('data');
        $conditions = json_decode($data, true);
        $result = $goodsService->getGoodsByConditions($conditions, array('goodsType', 'goodsRecord'));
        if ($result) {
            return $this->respondJson(array('goods' => $result));
        } else {
            return $this->respondJson(array('goods' => array(), 'code' => 1));
        }
    }

    /**
     * 新建商品
     * @param Request $request
     * @param GoodsService $goodsService
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request, GoodsService $goodsService)
    {
        $result = $goodsService->createGoods($request->request->all());
        if ($result) {
            return $this->respondJson(array('goods' => $result));
        } else {
            return $this->respondJson(array('goods' => array(), 'code' => 1));
        }
    }

    /**
     * 编辑商品
     * @param Request $request
     * @param GoodsService $goodsService
     * @return \Illuminate\Http\JsonResponse
     */
    public function modify(Request $request, GoodsService $goodsService)
    {
        $goodsInfo = $request->input('goods');
        if (is_string($goodsInfo)) {
            $goodsInfo = json_decode(str_replace('\'', '"', $goodsInfo), true);
        }
        $conditions = $request->input('conditions');
        if (is_string($conditions)) {
            $conditions = json_decode(str_replace('\'', '"', $conditions), true);
        }
        $result = $goodsService->modify($goodsInfo, $conditions);
        if ($result) {
            return $this->respondJson(array('prize' => $result));
        } else {
            return $this->respondJson(array('prize' => array(), 'code' => 1));
        }
    }

    /**
     * 删除商品
     * @param Request $request
     * @param GoodsService $goodsService
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request, GoodsService $goodsService)
    {
        $result = $goodsService->delete($request->request->all());
        if ($result) {
            return $this->respondJson(array('result' => 'success'));
        } else {
            return $this->respondJson(array('result' => 'fail', 'code' => 1));
        }
    }
}
